var sys = require("sys");
var http = require("http");
var fs = require("fs");

//*
function parse(rootObject) {
	sys.puts("parse");

	/*
	 for (var p in rootObject) {
	 // 方法
	 if ( typeof (obj[p]) == "function") {
	 // obj[p]();	 sys.puts("function");
	 } else {
	 // p 为属性名称，obj[p]为对应属性的值
	 // props+= p + "=" + obj[p] + "\t";	 sys.puts("property");
	 // parse_object(obj[p]);
	 }
	 }
	 */
	for (var i = 0; i < rootObject.length; i++) {
		parse_object(rootObject[i]);
	};
	sys.puts("parse end");
}

function parse_array(array) {
	// sys.puts("parse_array");
	for (var i = 0; i < array.length; i++) {
		var object = array[i];
		parse_object(object);
	};
	// sys.puts("parse_array end");
}

path = [];

function parse_object(object) {
	// sys.puts("parse_object");
	if (object.type == "folder") {
		//TODO:缺少对数组的类型判断
		path.push(object.name);
		parse_array(object.children);
		path.pop();

	} else if (object.type == "url") {
		analyse_item(object);
	} else {
		sys.puts("unexcepted");
	}
	// sys.puts("parse_object end");
}

var rooturis = new Object;
rooturis.count = 0;

function analyse_item(item) {
	var uri = item.url;
	// sys.puts(uri);
	var rooturi = uri.match(/http:\/\/.*?\//);

	if (undefined == rooturi) {
		var rooturi = uri.match(/https:\/\/.*?\//);
	}
	if (undefined != rooturi) {
		var array = rooturis[rooturi];
		if (undefined == array) {
			array = [];
			rooturis[rooturi] = array;
			rooturis.count++;
		}
		array.push(uri);
	}
	// sys.puts("analyse_item end");	return rooturi;
}

//*/
http.createServer(function(request, response) {
	// response.sendHeader(200, {
	// "Content-Type" : "text/html"
	// });
	fs.readFile("Bookmarks.json", function(err, data) {
		if (err) {
			sys.puts("err");
			throw err;
		}
		sys.puts("File is OK!");

		var obj = eval('(' + data + ')')
		sys.puts("start");
		parse(obj.roots.other.children);		// parse(obj.roots);
		sys.puts(rooturis.count);
		newData = JSON.stringify(rooturis);

		fs.writeFile('urls.json', newData, function(err) {
			if (err)
				throw err;
			console.log('has finished');
		});
		sys.puts("end");	});

	response.writeHead(200, {
		'Content-Type' : 'text/plain'
	});
	response.end('Hello World\n');

}).listen(8080);
sys.puts("Server running at http://localhost:8080/");
